﻿using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System.Configuration;
using System.Reflection;

namespace Armon.Lib.Database.SqlSugarLib
{
    public static class SqlSugarExtension
    {
        public static void AddSqlSugarSetup(this IServiceCollection services, ConnectionConfig config)
        {
            ArgumentNullException.ThrowIfNull(services);

            var client = new SqlSugarScope(config);
            var models = GetDbEntities();
            client.DbMaintenance.CreateDatabase();
            client.CodeFirst.SetStringDefaultLength(200).InitTables(models);
            services.AddSingleton<ISqlSugarClient>(o => client);
        }

        private static ConnectionConfig GetConfig(string connectionKey)
        {
            var connectionString = ConfigurationManager.ConnectionStrings[connectionKey].ConnectionString;

            var moreSettings = new ConnMoreSettings
            {
                IsAutoRemoveDataCache = true,
                DisableMillisecond = true,
                IsWithNoLockQuery = true,
                SqliteCodeFirstEnableDefaultValue = true,
            };
            var aopEvents = new AopEvents
            {
                OnLogExecuting = (sql, parameters) =>
                {
                    parameters.ToList().ForEach(p => sql.Replace(p.ParameterName, p.Value.ToString()));
                    var log = string.Join("\r\n", ["--------", "【SQL语句】：", sql]);
                    Console.WriteLine(log);
                },
            };

            return new ConnectionConfig
            {
                ConfigId = 1,
                ConnectionString = connectionString,
                DbType = DbType.Sqlite,
                IsAutoCloseConnection = true,
                InitKeyType = InitKeyType.Attribute,
                MoreSettings = moreSettings,
                AopEvents = aopEvents,
                LanguageType = LanguageType.Chinese
            };
        }

        private static Type[]? GetDbEntities()
        {
            var assemblies = Assembly.GetExecutingAssembly()
                .GetReferencedAssemblies();

            return Assembly.GetExecutingAssembly()
                .GetReferencedAssemblies()
                .Where(a => a.Name.EndsWith("Models"))
                .Select(a => Assembly.Load(a))
                .FirstOrDefault()?
                .GetTypes()
                .Where(t => t.GetCustomAttributes().Any(a => a is SugarTable))
                .ToArray();
        }
    }
}
